//
//  DGGPullDownMenuToolBar.m
//  demo
//
//  Created by 周家民 on 2020/8/11.
//  Copyright © 2020 mac. All rights reserved.
//

#import "DGGPullDownMenuButton.h"
#import "DGGPullDownMenuToolBar.h"
#import "UIColor+Extension.h"
#import "UIView+DGGPullDownMenuToolBar.h"

@interface DGGPullDownMenuContentView : UIView

@property (nonatomic, strong) UIColor *bgColor;

@end

@implementation DGGPullDownMenuContentView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.layer.masksToBounds = YES;
    }
    return self;
}

- (UIColor *)bgColor {
    if (!_bgColor) {
        _bgColor = [UIColor whiteColor];
    }
    return _bgColor;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    CGContextRef ctx    = UIGraphicsGetCurrentContext();
    CGFloat      radius = 12;
    CGContextMoveToPoint(ctx, 0, 0);
    CGContextAddLineToPoint(ctx, rect.size.width, 0);
    CGContextAddLineToPoint(ctx, rect.size.width, rect.size.height - radius);
    CGContextAddArc(ctx, rect.size.width - radius, rect.size.height - radius, radius, 0, M_PI_2, 0);
    CGContextAddLineToPoint(ctx, radius, rect.size.height);
    CGContextAddArc(ctx, radius, rect.size.height - radius, radius, M_PI_2, M_PI, 0);
    CGContextAddLineToPoint(ctx, 0, 0);
    CGContextSetFillColorWithColor(ctx, self.bgColor.CGColor);
    CGContextFillPath(ctx);
}

@end

@interface DGGPullDownMenuToolBar ()

/// 蒙板视图
@property (nonatomic, strong) UIView *mbView;

@property (nonatomic, strong) NSMutableArray<UIView *> *menuTitleViewList;

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) DGGPullDownMenuContentView *contentView;

@property (nonatomic, assign) NSInteger openIndex;

@property (nonatomic, assign) CGFloat contentViewCornerRadius;

@end

@implementation DGGPullDownMenuToolBar

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupUI];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat titleViewW = self.frame.size.width /self.menuTitleViewList.count;
    for (int i = 0; i < self.menuTitleViewList.count; i++) {
        UIView *titleView = self.menuTitleViewList[i];
        titleView.frame = CGRectMake(i * titleViewW, 0, titleViewW, self.frame.size.height);
    }
}

#pragma mark - getter
- (UIView *)mbView {
    if (!_mbView) {
        _mbView                 = [[UIView alloc] init];
        _mbView.backgroundColor = [UIColor dgg_ColorWithRed:0 green:0 blue:0 alpha:self.mbAlpha];
        _mbView.alpha           = 0;
        __weak typeof(self) weakSelf = self;
        _mbView.onClick = ^{
            [weakSelf foldWithAnimate:YES];
        };
    }
    return _mbView;
}

- (UIView *)containerView {
    if (!_containerView) {
        _containerView                     = [[UIView alloc] init];
        _containerView.layer.masksToBounds = YES;
        _containerView.hidden = YES;
        _containerView.backgroundColor     = [UIColor clearColor];
    }
    return _containerView;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView                 = [[DGGPullDownMenuContentView alloc] init];
        _contentView.backgroundColor = [UIColor clearColor];
        _contentView.bgColor = [[UIColor whiteColor] setDarkModeColor:[UIColor dgg_ColorWithRed:34 green:34 blue:35 alpha:1]];
    }
    return _contentView;
}

- (UIFont *)titleFont {
    if (!_titleFont) {
        _titleFont = [UIFont systemFontOfSize:14];
    }
    return _titleFont;
}

- (UIColor *)normalTitleColor {
    if (!_normalTitleColor) {
        _normalTitleColor = [[UIColor dgg_ColorWithRed:51 green:51 blue:51 alpha:1] setDarkModeColor:[UIColor whiteColor]];
    }
    return _normalTitleColor;
}

- (UIColor *)selectedTitleColor {
    if (!_selectedTitleColor) {
        _selectedTitleColor = [UIColor dgg_ColorWithRed:16 green:187 blue:184 alpha:1];
    }
    return _selectedTitleColor;
}

- (CGFloat)mbAlpha {
    if (_mbAlpha == 0) {
        _mbAlpha = 0.3;
    }
    return MAX(0, MIN(1, _mbAlpha));
}

- (NSMutableArray<UIView *> *)menuTitleViewList {
    if (!_menuTitleViewList) {
        _menuTitleViewList = [NSMutableArray array];
    }
    return _menuTitleViewList;
}

#pragma mark - setter

#pragma mark - custom
- (void)setupUI {
    self.contentViewCornerRadius = 12;
    self.openIndex = -1;
    self.backgroundColor = [[UIColor whiteColor] setDarkModeColor:[UIColor dgg_ColorWithRed:34 green:34 blue:35 alpha:1]];
}

- (void)bindOnView:(UIView *)view frame:(CGRect)frame {
    [view addSubview:self];
    self.frame = frame;
    [view addSubview:self.containerView];
    [self.containerView addSubview:self.mbView];
    [self.containerView addSubview:self.contentView];

    CGFloat containerY       = CGRectGetMaxY(frame);
    CGFloat containerH       = view.frame.size.height - containerY;
    self.containerView.frame = CGRectMake(frame.origin.x, CGRectGetMaxY(frame), frame.size.width, containerH);
    self.mbView.frame        = self.containerView.bounds;

    CGFloat contentViewH   = 80;
    self.contentView.frame = CGRectMake(0, -contentViewH, self.containerView.frame.size.width, contentViewH);
    
    [self reloadData];
}

- (void)openForIndex:(NSInteger)index animate:(BOOL)animate {
    if (index >= self.menuTitleViewList.count || index == self.openIndex) {
        return;
    }
    [self foldWithAnimate:NO];
    self.openIndex = index;
    UIView *titleView = self.menuTitleViewList[index];
    if ([titleView isKindOfClass:[DGGPullDownMenuButton class]]) {
        DGGPullDownMenuButton *titleButton = (DGGPullDownMenuButton *)titleView;
        titleButton.selected = !titleButton.isSelected;
    }
    void (^result)(void) = ^{
        self.mbView.alpha = 1;
        CGRect frame = self.contentView.frame;
        self.contentView.frame = CGRectMake(frame.origin.x, 0, frame.size.width, frame.size.height);
    };
    self.containerView.hidden = NO;
    
    UIView *customContentView = [self.dataSource toolBar:self contentViewForIndex:index];
    if (!customContentView) {
        customContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, 20)];
    }
    customContentView.layer.cornerRadius = self.contentViewCornerRadius;
    customContentView.layer.masksToBounds = YES;
    for (UIView *subView in self.contentView.subviews) {
        [subView removeFromSuperview];
    }
    
    [self.contentView addSubview:customContentView];
    CGRect contentFrame = self.contentView.frame;
    self.contentView.frame = CGRectMake(contentFrame.origin.x, contentFrame.origin.y, contentFrame.size.width, customContentView.frame.size.height);
    customContentView.frame = self.contentView.bounds;
    [self.contentView setNeedsDisplay];
    
    if (animate) {
        self.mbView.alpha = 0;
        [UIView animateWithDuration:0.2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:result
                         completion:nil];
    } else {
        result();
    }
}

- (void)foldWithAnimate:(BOOL)animate {
    self.openIndex = -1;
    for (DGGPullDownMenuButton *titleButton in self.menuTitleViewList) {
        titleButton.selected = NO;
    }
    void (^result)(void) = ^{
        self.mbView.alpha = 0;
        CGRect frame = self.contentView.frame;
        self.contentView.frame = CGRectMake(frame.origin.x, -frame.size.height, frame.size.width, frame.size.height);
    };
    void (^completion)(BOOL finished) = ^(BOOL finished) {
        self.containerView.hidden = YES;
    };
    if (animate) {
        [UIView animateWithDuration:0.2
                         animations:^{
                             result();
                         }
                         completion:completion];
    } else {
        result();
        completion(YES);
    }
}

- (void)reloadData {
    for (UIView *menuTitleView in self.menuTitleViewList) {
        [menuTitleView removeFromSuperview];
    }
    [self.menuTitleViewList removeAllObjects];
    for (UIView *subView in self.contentView.subviews) {
        [subView removeFromSuperview];
    }
    NSInteger titleCount = 0;
    if ([self.dataSource respondsToSelector:@selector(numberOfTitle:)]) {
        titleCount = [self.dataSource numberOfTitle:self];
    }
    if (titleCount < 1) {
        return;
    }
    for (int i = 0; i < titleCount; i++) {
        if ([self.dataSource respondsToSelector:@selector(toolBar:titleForIndex:)]) {
            NSString *title = [self.dataSource toolBar:self titleForIndex:i];
            DGGPullDownMenuButton *titleButton = [self createTitleButtonWithTitle:title];
            titleButton.tag = i;
            [self addSubview:titleButton];
            [self.menuTitleViewList addObject:titleButton];
        } else if ([self.dataSource respondsToSelector:@selector(toolBar:titleViewForIndex:)]) {
            UIView *titleView = [self.dataSource toolBar:self titleViewForIndex:i];
            [self addSubview:titleView];
            [self.menuTitleViewList addObject:titleView];
        } else {
            NSLog(@"缺少数据源代理方法toolBar:titleForIndex:或toolBar:titleViewForIndex:");
            return;
        }
    }
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (DGGPullDownMenuButton *)createTitleButtonWithTitle:(NSString *)title {
    DGGPullDownMenuButton *titleButton = [[DGGPullDownMenuButton alloc] init];
    titleButton.titleLabel.font = self.titleFont;
    titleButton.titleFont = self.titleFont;
    [titleButton setTitleColor:self.normalTitleColor forState:UIControlStateNormal];
    [titleButton setTitleColor:self.selectedTitleColor forState:UIControlStateSelected];
    [titleButton setTitle:title forState:UIControlStateNormal];
    __weak typeof(titleButton) weakTitleButton = titleButton;
    __weak typeof(self) weakSelf = self;
    titleButton.onClick = ^{
        if (weakTitleButton) {
            if (weakTitleButton.tag == weakSelf.openIndex) {
                [weakSelf foldWithAnimate:YES];
            } else {
                [weakSelf openForIndex:weakTitleButton.tag animate:YES];
            }
        }
    };
    return titleButton;
}

#pragma mark - event handler


@end
